package cn.edu.zzuli;

/**
 * @Date: 2021/3/6 16:15
 * @Author: 绯色下午茶
 * @Description:
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
class Ticket {
    /**
     * 创建可重入锁对象
     */
    private Lock lock = new ReentrantLock();
    private int number = 35;


    public void sale() {
        /**
         * lock.lock() 表示开启锁
         */
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第 " + (number--) + " 张,还剩下: " + number);

            }
        } catch (Exception e) {

        } finally {
//            关闭锁
            lock.unlock();
        }

    }
}

public class Juc01 {
    public static void main(String[] args) {

        final Ticket ticket = new Ticket();

//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 1; i <= 40; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "A").start();
//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 1; i <= 40; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "B").start();
//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 1; i <= 40; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "C").start();


        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 1; i <= 40; i++) {
                ticket.sale();
            }
        }, "C").start();


    }
}
